/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EconosimUI.java
 *
 * Created on Apr 27, 2009, 2:29:02 PM
 */

package display;

import java.awt.Dimension;
import javax.swing.*;
import java.awt.event.ItemEvent;


import MortgageCore.*;
import grapher.MetricViewer;
import simframe.simulation.SimViewer;
import simframe.simulation.Time;

import viewer.parameters.ParmView;

/**
 *
 * @author karakots
 */
public class EconosimScrollUI extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    static final int kWorldWidth = 1600;
    static final int kWorldHeight = 600;

    MetricViewer grapher;

    SavingsSim sim;
    Thread simThread;

      // this is days per second
    static final int minDays = 1;
    static final int maxDays = 60;

    /** Creates new form EonoSimUI */
    public EconosimScrollUI() {
    	initComponents();
        SpinnerNumberModel model = new SpinnerNumberModel(maxDays,1,maxDays+1,1);
        daysPerSecSpinner.setModel(model);
     
        sim = new SavingsSim(1000, 10, true, false);
        
        //
        // Map View
        //
      // myCanvas = new MortgageCoreView(sim, 0, 0, 1, 1);

        //mapPanel.add(myCanvas);
     //   mapPanel.add(myCanvas);
        //mapPanel.setViewportView(myCanvas);

        SimViewer dayView = new SimViewer() {

            public void update(long t) {
                dayNumLabel.setText("Day " + Long.toString(t/Time.Day));
            }

            public void reset() {
               dayNumLabel.setText("reset");
            }

        };


        
      //  sim.addViewer(myCanvas, 7);

        sim.addViewer(dayView, 10);

     //   myCanvas.reset();
        
        //myCanvas.setBounds(0, 0, kWorldWidth, kWorldHeight);
        //
        // metrics
        //
        grapher = new MetricViewer();

        grapher.setBounds(metricsCanvasPanel.getBounds());
        sim.addMetricDisplay(grapher);

        metricsPanel.add(grapher);

        setCanvasSize(kWorldWidth, kWorldHeight);

        //
        //  metrics legend
        //
        // vertical flow
        /*
        Map<String, Color> legend = metrics.getLegend();
        javax.swing.JPanel panel = new javax.swing.JPanel(new GridBagLayout());
        javax.swing.JPanel legendPanel = new javax.swing.JPanel(new GridLayout(legend.size(), 1));

        for(String name : legend.keySet()) {
        	JLabel label = new JLabel();
        	label.setText(name);
        	//label.setForeground(legend.get(name));
        	legendPanel.add(label);
        }
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 0;
        panel.add(legendPanel, c);
        metricsPanel.add(panel);
        */

        setDaysToRun();

    }

    void setCanvasSize(int width, int height) {
        if (width > kWorldWidth) {
            width = kWorldWidth;
        }
        if (height > kWorldHeight) {
            height = kWorldHeight;
        }
      //  myCanvas.setBounds(0, 0, width, height);
    }

    private void setDaysToRun()
    {
        // this is the simulation speed
        double value = ((SpinnerNumberModel)daysPerSecSpinner.getModel()).getNumber().intValue();
        int numDays = (int) (minDays + (maxDays * value/(maxDays + 1)));
        sim.DaysPerSecond( numDays);
        System.out.println("Sim Speed = " + Integer.toString(numDays) + " days per second");
    }

    private void showHomes(boolean show) {
       // myCanvas.showHomes(show);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        metricsPanel = new javax.swing.JPanel();
        metricsCanvasPanel = new javax.swing.JPanel();
        simControlPanel = new javax.swing.JPanel();
        runPauseButton = new javax.swing.JToggleButton();
        resetButton = new javax.swing.JButton();
        daysPerSecSpinner = new javax.swing.JSpinner();
        daysPerSecLabel = new javax.swing.JLabel();
        showHomesChkBox = new javax.swing.JCheckBox();
        dayNumLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        mapContainer = new javax.swing.JPanel();
        mapPanel = new java.awt.ScrollPane();

        org.jdesktop.layout.GroupLayout jFrame1Layout = new org.jdesktop.layout.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        metricsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Metrics"));

        metricsCanvasPanel.setOpaque(false);

        org.jdesktop.layout.GroupLayout metricsCanvasPanelLayout = new org.jdesktop.layout.GroupLayout(metricsCanvasPanel);
        metricsCanvasPanel.setLayout(metricsCanvasPanelLayout);
        metricsCanvasPanelLayout.setHorizontalGroup(
            metricsCanvasPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 496, Short.MAX_VALUE)
        );
        metricsCanvasPanelLayout.setVerticalGroup(
            metricsCanvasPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 240, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout metricsPanelLayout = new org.jdesktop.layout.GroupLayout(metricsPanel);
        metricsPanel.setLayout(metricsPanelLayout);
        metricsPanelLayout.setHorizontalGroup(
            metricsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, metricsCanvasPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        metricsPanelLayout.setVerticalGroup(
            metricsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(metricsCanvasPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        simControlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sim Control"));

        runPauseButton.setText("Start");
        runPauseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runPauseButtonActionPerformed(evt);
            }
        });

        resetButton.setText("Reset");
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        daysPerSecSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                daysPerSecSpinnerStateChanged(evt);
            }
        });

        daysPerSecLabel.setText("days/second:");

        showHomesChkBox.setSelected(true);
        showHomesChkBox.setText("Show Homes");
        showHomesChkBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                showHomesChkBoxItemStateChanged(evt);
            }
        });
        showHomesChkBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showHomesChkBoxActionPerformed(evt);
            }
        });

        dayNumLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jButton1.setText("Parameters");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout simControlPanelLayout = new org.jdesktop.layout.GroupLayout(simControlPanel);
        simControlPanel.setLayout(simControlPanelLayout);
        simControlPanelLayout.setHorizontalGroup(
            simControlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(simControlPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(dayNumLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(simControlPanelLayout.createSequentialGroup()
                .add(10, 10, 10)
                .add(simControlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(simControlPanelLayout.createSequentialGroup()
                        .add(24, 24, 24)
                        .add(daysPerSecSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(daysPerSecLabel)))
            .add(showHomesChkBox)
            .add(simControlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                .add(org.jdesktop.layout.GroupLayout.LEADING, resetButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(org.jdesktop.layout.GroupLayout.LEADING, runPauseButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 114, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(jButton1)
        );
        simControlPanelLayout.setVerticalGroup(
            simControlPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(simControlPanelLayout.createSequentialGroup()
                .add(dayNumLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(runPauseButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(resetButton)
                .add(4, 4, 4)
                .add(daysPerSecLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(daysPerSecSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(showHomesChkBox)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        mapContainer.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        mapContainer.setOpaque(false);
        mapContainer.setPreferredSize(new java.awt.Dimension(600, 640));
        mapContainer.setRequestFocusEnabled(false);
        mapContainer.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                mapContainerComponentResized(evt);
            }
        });

        org.jdesktop.layout.GroupLayout mapContainerLayout = new org.jdesktop.layout.GroupLayout(mapContainer);
        mapContainer.setLayout(mapContainerLayout);
        mapContainerLayout.setHorizontalGroup(
            mapContainerLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mapContainerLayout.createSequentialGroup()
                .add(mapPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                .addContainerGap())
        );
        mapContainerLayout.setVerticalGroup(
            mapContainerLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mapContainerLayout.createSequentialGroup()
                .add(mapPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 640, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mapContainer, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(2, 2, 2)
                .add(metricsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(simControlPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(mapContainer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 654, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(metricsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(simControlPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void runPauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runPauseButtonActionPerformed
        if (sim.stopped()) {
            if (runPauseButton.getText().compareTo("Start") == 0) {
                sim.reset();
            }
            setDaysToRun();
            simThread = new Thread(sim);
            simThread.start();
            runPauseButton.setText("Pause");
            resetButton.setEnabled(false);
        } else {
        	sim.stop();
        	simThread = null;
        	runPauseButton.setText("Continue");
            resetButton.setEnabled(true);
        }

    }//GEN-LAST:event_runPauseButtonActionPerformed

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        // TODO add your handling code here:
        runPauseButton.setText("Start");
        sim.reset();
    }//GEN-LAST:event_resetButtonActionPerformed

    private void mapContainerComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_mapContainerComponentResized
        // for some reason, need to manually resize the scroll pane
        // maybe because it is an awt and not a swing scrollpane
        // because swing scroll pane wil not work with heavyweight componets like canvas
        Dimension panelSize = new Dimension(mapPanel.getSize());
        int frameWidth = mapContainer.getWidth();
        panelSize.setSize(frameWidth-16, panelSize.getHeight());
        mapPanel.setSize(panelSize);
    }//GEN-LAST:event_mapContainerComponentResized

    private void daysPerSecSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_daysPerSecSpinnerStateChanged
        // TODO add your handling code here:
        setDaysToRun();
    }//GEN-LAST:event_daysPerSecSpinnerStateChanged

    private void showHomesChkBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showHomesChkBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_showHomesChkBoxActionPerformed

    private void showHomesChkBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_showHomesChkBoxItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED)
            showHomes(true);
        else if (evt.getStateChange() == ItemEvent.DESELECTED)
            showHomes(false);
    }//GEN-LAST:event_showHomesChkBoxItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (parmView == null) {
            parmView = new ParmView(sim.getParameters());

            parmView.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        }

        parmView.setVisible(true);
        
//        Thread parmThread =  new Thread(new Runnable() {
//            public void run() {
//               parmView.setVisible(true);
//            }
//        });
//
//        parmThread.start();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EconosimScrollUI().setVisible(true);
            }
        });
    }

     JFrame parmView = null;
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel dayNumLabel;
    private javax.swing.JLabel daysPerSecLabel;
    private javax.swing.JSpinner daysPerSecSpinner;
    private javax.swing.JButton jButton1;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mapContainer;
    private java.awt.ScrollPane mapPanel;
    private javax.swing.JPanel metricsCanvasPanel;
    private javax.swing.JPanel metricsPanel;
    private javax.swing.JButton resetButton;
    private javax.swing.JToggleButton runPauseButton;
    private javax.swing.JCheckBox showHomesChkBox;
    private javax.swing.JPanel simControlPanel;
    // End of variables declaration//GEN-END:variables

}
